/**
	@import Config.js

*/

// 静态页面内容
Template.registerHelper('content', function(){
	pageModel = Session.get('staticWebContent');
	return pageModel.content;
});

// 网站名称
Template.registerHelper('siteName', function(){
	configModel = Config.findOne({});
	return configModel ? configModel.settings.siteName : "";
});

// 导航条 仅对静态页面
Template.registerHelper('navmenu', function(){
	menu = NavMenu.find({}, {sort: {order: 1}}).fetch();
	return navMenuTag(menu);
});


function navMenuTag(menu) {
	var output = "";
	for (var i = 0; i < menu.length; i++) {
		item = menu[i];
		li_class = item.page == Session.get("page") ? "active" : "";
		href = item.url ? " href='" + item.url + "'" : "";
		link = "<a" + href + ">" + item.label + "</a>";

		output = output + "<li =class='" + li_class + "'>" + link + "</li>";
	}
	return output;
}

Template.signin.events({
	'click button': function (event) {
		// ...
		event.preventDefault();
		var formData = $("form.form-signin").serialize();
		
		$.post("/api/user/signin",formData,function(data){
			data = JSON.parse(data);
			console.log(data);
			if(data.code === 200){
				$(window.location).attr('href', '/');
			} else {
				FlashMessages.sendError(data.data.reason);
			}
		});
	}
});

Template.signup.onRendered(function(){
	var formData = $("form.form-signup");
	formData.validate({
		rules:{
			email:{
				required: true,
				email:true
			},
			username:{
				required: true,
				maxlength: 20,
				minlength: 8
			},
			password:{
				required: true,
				maxlength: 20,
				minlength: 8
			},
			password2:{
				equalTo:"#signup-password-1"
			}
		},
		messages:{
			email:{
				required: "请输入您的邮箱地址",
				email: "请输入正确的邮箱地址"
			},
			username:{
				required: "请输入您的用户名",
				maxlength: "用户名长度不能超过20",
				minlength: "用户名长度不能少于8"
			},
			password:{
				required: "请输入您的密码",
				maxlength: "密码长度不能超过20",
				minlength: "密码长度不能少于8"
			},
			password2:{
				equalTo: "请输入相同的密码"
			}
		},
		submitHandler: function(){
			var formData = $("form.form-signup").serialize();
			console.log(formData);

			$.post("/api/user/signup", formData, function(data){
				data = JSON.parse(data);
				console.log(data);
				if(data.code === 200){
					$(window.location).attr('href', '/');
				} else {
					FlashMessages.sendError(data.data.reason);
				}
			});
		}
	});
});
